//
//  PhysicalAndPOBoxAddressView.swift
//  GreenDeal
//
//  Created by Moennig Q on 2023/3/15.
//

import UIKit
import RxGesture
import RxCocoa
import RxSwift
class PhysicalAndPOBoxAddressViewModel: NSObject {
    //
    var address_type: AddressType = .none {
        didSet{
            self.address_type_value = address_type.rawValue
        }
    }
    @objc dynamic var address_type_value: String = ""
    //physical
    @objc dynamic var physicalAddress = PhysicalAddressViewModel()
    //po box
    var delivery_type: String = "PO Box"
    @objc dynamic var delivery_number: String = ""
    @objc dynamic var suburb: String = ""
    @objc dynamic var state: String = ""
    @objc dynamic var post_code: String = ""
    //
    var post_code_display_name: String {
        var returnStr = ""
        if self.suburb != ""{
            returnStr = self.suburb
        }
        if self.state != ""{
            returnStr += " " + self.state
        }
        if self.post_code != ""{
            returnStr += " " + self.post_code
        }
        return returnStr
    }
    var po_box_full_address: String {
        return self.delivery_type + " " + self.delivery_number + ", " + self.suburb + " " + self.state + " " + self.post_code
    }
}
class PhysicalAndPOBoxAddressView: UIView {
    //
    lazy var disposeBag = DisposeBag()
    var scrollToAddAddressViewClosure: (()->Void)?
    var viewModel = PhysicalAndPOBoxAddressViewModel()
    let physicalTypeLabel = OptionTypeLabel(R.string.localizable.physical(),topBottomPadding: 12)
    let poBoxTypeLabel = OptionTypeLabel(R.string.localizable.poBox(), topBottomPadding: 12)
    lazy var addressTypeRequiredLabel: BaseLabel = {
        return ViewFactory.shared.generateRequiredLabel()
    }()
    let addressContent = UIView()
    //选择physical，编辑地址
    lazy var editPhysicalAddress = PhysicalAddressView()
    //选择PO Box的信息
    lazy var poBoxNumberTextfield = TextFieldWithRequiredView()
    lazy var postcodeTextfield = TextFieldWithRequiredView(.postCode)
    //内容的左右上下边距
    var leftRightMargin: CGFloat = 0
    var topBottomMargin: CGFloat = 0
    //IB init
    required init?(coder aDecoder: NSCoder) {
        super.init(coder:aDecoder)
    }
    //纯代码创建
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.setUpView()
    }
    init(leftRightMargin: CGFloat = 0, topBottomMargin: CGFloat = 0,postalAddressFlag: Bool = false) {
        super.init(frame: CGRect.zero)
        self.leftRightMargin = leftRightMargin
        self.topBottomMargin = topBottomMargin
        self.editPhysicalAddress.dealIfCheckStreetNoAndStreetName(postalAddressFlag)
        self.setUpView()
        
    }
    func setUpView() {
        //physical
        self.addSubview(physicalTypeLabel)
        physicalTypeLabel.snp.makeConstraints { (make) in
            make.top.equalTo(topBottomMargin)
            make.left.equalTo(leftRightMargin)
            make.width.height.greaterThanOrEqualTo(0)
        }
        //PO box
        self.addSubview(poBoxTypeLabel)
        poBoxTypeLabel.snp.makeConstraints { (make) in
            make.left.equalTo(physicalTypeLabel.snp.right).offset(8)
            make.right.equalTo(-leftRightMargin)
            make.top.width.height.equalTo(physicalTypeLabel)
        }
        //
        self.addSubview(addressTypeRequiredLabel)
        addressTypeRequiredLabel.snp.makeConstraints { make in
            make.top.equalTo(physicalTypeLabel.snp.bottom).offset(Constant.TitleTextMargin)
            make.left.equalTo(physicalTypeLabel)
            make.height.width.greaterThanOrEqualTo(0)
        }
        
        //
        addressContent.backgroundColor = .white
        self.addSubview(addressContent)
        addressContent.snp.makeConstraints { (make) in
            make.top.equalTo(addressTypeRequiredLabel.snp.bottom).offset(Constant.TopBottomMargin)
            make.left.equalTo(physicalTypeLabel)
            make.right.equalTo(poBoxTypeLabel)
            make.height.greaterThanOrEqualTo(0)
            make.bottom.equalToSuperview()
        }
        
        //选择Physical
        physicalTypeLabel.rx.tapGesture().when(.recognized).subscribe(onNext: { [weak self] _ in
            //重复点击physical，不做处理
            if self?.viewModel.address_type == .physical { return }
            self?.changeAddressType(.physical)
            self?.scrollToAddAddressViewClosure?()
        }).disposed(by: self.disposeBag)
        //选择poBox
        poBoxTypeLabel.rx.tapGesture().when(.recognized).subscribe (onNext: { [weak self] _ in
            //重复点击po box，不做处理
            if self?.viewModel.address_type == .poBox { return }
            self?.changeAddressType(.poBox)
            self?.scrollToAddAddressViewClosure?()
        }).disposed(by: self.disposeBag)
    }
    //address type = Physical时，UI初始化
    private func initUIByPhysical(){
        //创新选择address type时，重置内容
        self.addressContent.addSubview(editPhysicalAddress)
        editPhysicalAddress.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.greaterThanOrEqualTo(0)
            make.bottom.equalTo(-topBottomMargin)
        }
        
    }
    //address type = Postal时，UI初始化
    private func initUIByPostal(){
        //poBoxNumberLabel
        let poBoxNumberLabel = LabelWithRedStarView(R.string.localizable.poBoxNumber())
        self.addressContent.addSubview(poBoxNumberLabel)
        poBoxNumberLabel.snp.makeConstraints { make in
            make.left.top.equalToSuperview()
            make.height.width.greaterThanOrEqualTo(0)
        }
        //poBoxNumberTextfield
        poBoxNumberTextfield.textField.clearButtonMode = .always
        self.addressContent.addSubview(poBoxNumberTextfield)
        poBoxNumberTextfield.snp.makeConstraints { make in
            make.top.equalTo(poBoxNumberLabel.snp.bottom).offset(Constant.TitleTextMargin)
            make.left.equalTo(poBoxNumberLabel)
            make.right.equalToSuperview()
            make.height.greaterThanOrEqualTo(0)
        }
        //postcodeLabel
        let postcodeLabel = LabelWithRedStarView(R.string.localizable.postcode())
        self.addressContent.addSubview(postcodeLabel)
        postcodeLabel.snp.makeConstraints { make in
            make.top.equalTo(poBoxNumberTextfield.snp.bottom).offset(Constant.TopBottomMargin)
            make.left.equalTo(poBoxNumberLabel)
            make.height.width.greaterThanOrEqualTo(0)
        }
        //postcodeTextfield
        postcodeTextfield.textField.placeholder = R.string.localizable.typePostcodeToSearch()
        postcodeTextfield.textField.clearButtonMode = .always
        postcodeTextfield.textField.keyboardType = .numberPad
        self.addressContent.addSubview(postcodeTextfield)
        postcodeTextfield.snp.makeConstraints { make in
            make.top.equalTo(postcodeLabel.snp.bottom).offset(Constant.TitleTextMargin)
            make.left.right.equalTo(poBoxNumberTextfield)
            make.height.greaterThanOrEqualTo(0)
            make.bottom.equalTo(-topBottomMargin)
        }
        //
        postcodeTextfield.textField.showRightImageView("edit_address_search_icon") {[weak self] in
            guard let strongSelf = self else {return}
            strongSelf.endEditing(true)
            let postCode = strongSelf.viewModel.post_code
            Tool().showSearchAddressDictionaryView(type: .postcode,showPleaseSleectFlag: false,title: R.string.localizable.suburb(),defaultSearchValue: postCode) {[weak self] (result) in
                guard let strongSelf = self else { return}
                strongSelf.setSuburbInfo(result)
            }

        }
        //编辑完自动获取时间
        postcodeTextfield.editingDidEndClosure = { [weak self]  (content) in
            guard let strongSelf = self else {return}
            //0.现将当前值赋值上，只保留post code，将state，suburb情况
            strongSelf.checkPostCode(content)
        }
        //编辑完自动获取时间
        poBoxNumberTextfield.editingDidEndClosure = {[weak self] (data)in
            guard let strongSelf = self else {return }
            strongSelf.viewModel.delivery_number = data
        }
    }
    //MARK: - 根据输入的post code查找相关的suburb state info,直接复制
    private func setSuburbInfo(_ addressModel: PhysicalAddressViewModel){
        //设置文本
        self.postcodeTextfield.textField.text = addressModel.post_code_display_name
        //数据
        self.viewModel.post_code = addressModel.post_code
        self.viewModel.state = addressModel.state
        self.viewModel.suburb = addressModel.suburb
        if addressModel.state != "" && addressModel.suburb != "" {
            self.postcodeTextfield.hideInvalidMsg()
        }
    }
    //MARK: - 选择地址类型
    func changeAddressType(_ addressType: AddressType){
        //remove all subviews
        for subview in self.addressContent.subviews{
            subview.removeFromSuperview()
        }
        self.physicalTypeLabel.setUnSelect()
        self.poBoxTypeLabel.setUnSelect()
        
        self.viewModel.address_type = addressType
        self.addressTypeRequiredLabel.text = ""
        if addressType == .none {
            return
        }
        if addressType == .physical {//physical
            self.physicalTypeLabel.setSelect()
            self.poBoxTypeLabel.setUnSelect()
            self.initUIByPhysical()
            
        }else {// postal
            self.physicalTypeLabel.setUnSelect()
            self.poBoxTypeLabel.setSelect()
            self.initUIByPostal()
        }
    }
    
    //MARK: - PO postcode根据输入的post code查找相关的suburb state info,直接复制
    private func checkPostCode(_ content: String){
        if content == self.viewModel.post_code_display_name {//只是切换焦点，没有变化就不处理
            return
        }
        guard content.count >= 4 else {
            self.viewModel.post_code = ""
            self.viewModel.state = ""
            self.viewModel.suburb = ""
            return
        }
        let postCode = String(content.suffix(4))//取最后四位，因为postcodeTextfield显示的是suburb + state + postcode的组合
        let list = DBManager.shared.getSuburbListByPostcode(postCode)
        if list.count == 0{//没有地址返回
            self.postcodeTextfield.showInvalidMsg(R.string.localizable.noSuburbMatchingThatPostcodeFound())
            let addressModel = PhysicalAddressViewModel()
            addressModel.post_code = postCode
            self.setSuburbInfo(addressModel)
        }else{
            if list.count == 1 {//只返回一个，就自动复制
                self.setSuburbInfo(list[0])
            }else{//返回多个地址，自动弹出搜索框
                let addressModel = PhysicalAddressViewModel()
                addressModel.post_code = postCode
                self.setSuburbInfo(addressModel)
                Tool().showSearchAddressDictionaryView(type: .postcode,showPleaseSleectFlag: false,title: R.string.localizable.suburb(),defaultSearchValue: addressModel.post_code) {[weak self] (result) in
                    guard let strongSelf = self else { return}
                    if result.post_code == ""{//为空表示没有选择suburb，直接关闭了搜索框
                        strongSelf.postcodeTextfield.showInvalidMsg(R.string.localizable.pleaseSelectOneSuburb())
                    }else{
                        strongSelf.setSuburbInfo(result)
                    }
                    
                }
            }
        }
    }
    //设置数据
    func setData(_ model: PhysicalAndPOBoxAddressViewModel){
        self.viewModel = model
        self.editPhysicalAddress.setData(self.viewModel.physicalAddress)
        self.poBoxNumberTextfield.textField.text = self.viewModel.delivery_number
        self.postcodeTextfield.textField.text = self.viewModel.post_code_display_name
        self.changeAddressType(self.viewModel.address_type)
    }
    //MARK: - 只用于已创建Job的信息编辑， 进入编辑界面如果save 按钮不可用，要给与相应提示
    func validateAllRequiredFieldWhenEdit(){
        //检查address type
        if self.viewModel.address_type == .none{
            self.addressTypeRequiredLabel.text = R.string.localizable.thisIsRequired()
        }else{
            let addressType = self.viewModel.address_type
            if addressType == .physical {
                self.editPhysicalAddress.validateAllRequiredFieldWhenEdit()
            }else{//检查po box
                //po box number
                self.poBoxNumberTextfield.checkIfStandardValid()
                self.postcodeTextfield.checkIfStandardValid()
                if self.postcodeTextfield.validStatus.value == .valid {
                    if viewModel.state == "" && viewModel.suburb == "" {//为空才校验
                        self.postcodeTextfield.showInvalidMsg(R.string.localizable.pleaseSelectOneSuburb())
                    }
                }
            }
        }
    }
    
    //检查postcode信息是否合法
    private func checkIfPostcodeInfoValid(postcode: String, state: String, suburb: String)->String{
        if postcode == "" || state == "" || suburb == ""{
            if postcode == "" {
                return R.string.localizable.thisIsRequired()
            }else if state == "" || suburb == ""{
                return R.string.localizable.pleaseSelectOneSuburb()
            }
        }
        return ""
    }
}

